<?php


class BaseModel
{
    var $db = null;

    // 数据库表名
    var $table = '';

    // 表前缀 
    var $_prefix = '';
	
    var $_page_rows = 20;	


    function __construct()
    {
        $this->BaseModel();
    }

    function BaseModel()
    {
        $this->db =& $GLOBALS['SCup']->_get_db();
        $this->_prefix = DB_PREFIX;
        $this->table = $this->_prefix . $this->table;
    }
	
     //插入，修改语句的产生及执行
    function IU_Sql_Exe($param = array ('table' => '','data' => array(), 'mode' => 'INSERT','conditions' => ''))
    {   
	    if(!isset($param['table']))
		{
		 $param['table'] ='';
		}
		
	    if(!isset($param['data']))
		{
		 $param['data'] =array();
		}		
	    if(!isset($param['conditions']))
		{
		 $param['conditions'] ='';
		}
	    if(!isset($param['mode']))
		{
		 $param['mode'] ='INSERT';
		}		

	     empty($param['table'])?$table = $this->table:$table = $param['table'];		 
		 if(empty($param['data']))
		 {
		  return false;
		 }
        $sql = '';
		
		if(empty($param['mode']))$param['mode'] = 'INSERT';
		
        if ($param['mode'] == 'INSERT')
        {
         $sql = "INSERT INTO `$table`(`".implode('`,`', array_keys($param['data']))."`) VALUES('".implode("','", $param['data'])."')";
        }
        else if($param['mode'] == 'UPDATE')
        {
             if($param['conditions'])
		     {
			     foreach($param['data'] as $k=>$v)
			     {
				   $sql .= ", `$k`='$v'";
			     }				 
			     $sql = substr($sql, 1);
				$sql = "UPDATE `$table` SET $sql WHERE ".$param['conditions']." ";	
				 
		     }
			 else
			 {
			     $sql = "REPLACE INTO `$table`(`".implode('`,`', array_keys($param['data']))."`) VALUES('".implode("','", $param['data'])."')";				 
			 }	
			 
			 			 
        }

        if ($sql)
        {
			return $this->db->query($sql);
        }
        else
        {
            return false;
        }
    }
	
	//查询语句的产生及执行
    function S_Sql_Exe($param = array('table' =>'','fields' =>'*','conditions' =>'', 'order' =>'','limit' =>'','return' =>'all'))
    {  
	    if(!isset($param['table']))
		{
		 $param['table'] ='';
		}
		
	    if(!isset($param['fields']))
		{
		 $param['fields'] ='*';
		}		
	    if(!isset($param['conditions']))
		{
		 $param['conditions'] ='';
		}
	    if(!isset($param['order']))
		{
		 $param['order'] ='';
		}		
	    if(!isset($param['limit']))
		{
		 $param['limit'] ='';
		}		
	    if(!isset($param['return']))
		{
		 $param['return'] ='all';
		}
         $order = '';
		 $conditions = '';
		 $limit = '';			
	    ($param['table'] == '')?$tables = $this->table:$tables = $param['table']; 
		
		if(empty($param['fields']))$param['fields'] = '*';
		
		if(empty($param['return']))$param['return'] = 'all';

		
        // 条件(WHERE)
        $param['conditions'] && $conditions = ' WHERE ' . $param['conditions'] .' ';
        if (defined("SX_SELECT_STR")) 
		{
		    if($conditions)
			{
			   $conditions.= ' and ' .SX_SELECT_STR . ' ';
			}
			else
			{
			   $conditions.= ' WHERE ' .SX_SELECT_STR . ' ';
			}
        }			

        // 排序(ORDER BY) desc表示倒序,asc表示正序(这个是默认的) 
        $param['order'] && $order = ' ORDER BY ' . $param['order'] . ' ';

        // 分页(LIMIT)
        $param['limit'] && $limit = ' LIMIT ' . $param['limit'] . ' ';
		
		$sql = "SELECT ".$param['fields']." FROM {$tables}{$conditions}{$order}{$limit}";

		if($param['return'] == 'one')
		{
		return $this->db->get_one($sql);		
		}
		else
		{
		return $this->db->get_all($sql);		
		}
    }
			
	//删除语句的产生及执行
    function D_Sql_Exe($param = array('table' => '','conditions' => ''))
    {  
	    if(!isset($param['table']))
		{
		 $param['table'] ='';
		}	
	    if(!isset($param['conditions']))
		{
		 $param['conditions'] ='';
		}

		 $conditions = '';
			 
	    if(!($conditions = $param['conditions']))
		{
		return false;
		}
		
	    empty($param['table'])?$table = $this->table:$table = $param['table']; 
        return $this->db->query("DELETE FROM {$table} WHERE {$conditions}");  
    }

	function Page_And_S_Sql_Exe($param = array (
		'table' => '',
		'fields' => '*',
		'conditions' => '',
		'order' => '',
		'limit' => '',
		'return' => 'all',
		'url' => ''
	)) { 
	    if(!isset($param['table']))
		{
		 $param['table'] ='';
		}
		
	    if(!isset($param['fields']))
		{
		 $param['fields'] ='*';
		}		
	    if(!isset($param['conditions']))
		{
		 $param['conditions'] ='';
		}
	    if(!isset($param['order']))
		{
		 $param['order'] ='';
		}		
	    if(!isset($param['limit']))
		{
		 $param['limit'] ='';
		}		
	    if(!isset($param['return']))
		{
		 $param['return'] ='all';
		}
	    if(!isset($param['url']))
		{
		 $param['url'] ='';
		}	
         $order = '';
		 $conditions = '';
		 $limit = '';			
			$fields = '';
			$return = '';
			$url = '';
		($param['table'] == '') ? $tables = $this->table : $tables = $param['table'];

		if (empty ($param['fields']))
			$param['fields'] = '*';

		if (empty ($param['return']))
			$param['return'] = 'all';
		$param['fields'] && $fields = '' . $param['fields'] ;

		$param['return'] && $return = '' . $param['return'] ;
		// 条件(WHERE)
		$param['conditions'] && $conditions = '' . $param['conditions'] . ' ';

		// 排序(ORDER BY) desc表示倒序,asc表示正序(这个是默认的) 
		$param['order'] && $order = '' . $param['order'] . ' ';

		// 分页(LIMIT)
		$param['limit'] && $limit = '' . $param['limit'] . ' ';
		$rows = $this->_page_rows;		
        if($param['limit'])
		{
			$arr = explode(',', $param['limit']);

            if(isset($arr[0])&&isset($arr[1]))
			{
			 $rows = ($arr[1]-$arr[0]);
			}
			
			if(isset($arr[0])&&!isset($arr[1]))
			{
			 $rows=$arr[0];
			}
			
			if(!isset($arr[0])&&isset($arr[1]))
			{
			$rows=$arr[1];
			}

				
		} 
		$param['url'] && $url = '' . $param['url'];

		 $info = array();
		 $info['page'] = $this->Page(array('table'=>"{$tables}",'conditions' =>"{$conditions}",'url' => "{$url}",'rows' =>"{$rows}"));		
		 
		 $info['data'] = $this->S_Sql_Exe(array('table'=>"{$tables}",'fields'=> "{$fields}",'conditions' =>"{$conditions}",'order' =>"{$order}",'limit' =>$info['page']['sql_limit'],'return' => '{$return}'));
    
		 return $info;
    }

    //分页
	function Page($param = array('table' => '','conditions' => '','url' =>'?','rows' =>'','total' => ''))
	{
	    if(!isset($param['table']))
		{
		 $param['table'] ='';
		}		
	    if(!isset($param['conditions']))
		{
		 $param['conditions'] ='';
		}
	    if(!isset($param['url']))
		{
		 $param['url'] ='?';
		}		
	    if(!isset($param['rows']))
		{
		 $param['rows'] ='';
		}		
	    if(!isset($param['total']))
		{
		 $param['total'] ='';
		}					
	    if(!isset($_GET['page']))
		{
		 $_GET['page'] =1;
		}	
         $page = empty($_GET['page']) ? 1 : intval($_GET['page']);

		 ($param['table'] == '')?$tables = $this->table:$tables = $param['table']; 
		 $url = $param['url'];
		 ($param['rows']=='')?$param['rows'] = $this->_page_rows:'';
		 
		 ($param['conditions']=='')?$param['conditions'] = '':$param['conditions'] = ' where '.$param['conditions'];		 
		 if (defined("SX_SELECT_STR")) 
		 {
		    if($param['conditions'])
			{
			   $param['conditions'] .= ' and ' .SX_SELECT_STR;
			}
			else
			{
			   $param['conditions'] .= ' WHERE ' .SX_SELECT_STR;
			}
         }	 

	     //当存在$total的时候.就不用再读数据库
	     if(!$param['total']&&$tables)
		 {
		      $query=$this->db->get_one("SELECT COUNT(*) AS num  FROM $tables ".$param['conditions']." ");
		      $param['total']=$query['num'];

	     }


	     $totalpage=@ceil($param['total']/$param['rows']);

		 
	     $nextpage=$page+1;
	     $uppage=$page-1;
		 
	     if($nextpage>$totalpage)
		 {
		      $nextpage=$totalpage;
	     }
		 
	     if($uppage<1)
		 {
		      $uppage=1;
	     }
	     $s=$page-3;
	     if($s<1)
		 {
		      $s=1;
	     }
	     $b=$s;
	     for($i=0;$i<6;$i++)
		 {
		      $b++;
	     }
	     if($b>$totalpage)
		 {
		      $b=$totalpage;
	     }
		 
		 $view = &$GLOBALS['SCup']->_get_view();
		 $page_array = array();
		 
	     for($j=$s;$j<=$b;$j++)
		 {
		      if($j==$page)
			  {
			        $page_array['curr']['num'] = $j;
					$page_array['curr']['url'] = $view->_write_url("$url&page=$j");
		      }
			  else
			  {      
			        $page_array['plist'][$j] = $view->_write_url("$url&page=$j");			         
		      }
	      }
		  
        if(!isset($page_array['curr']))
		{
		  $page_array['curr']['num'] =1;
		  $page_array['curr']['url'] = $view->_write_url("$url&page=1"); 
		}
        if(!isset($page_array['list']))
		{
		  $page_array['list']['url'] = $view->_write_url("$url&page=1"); 
		}		  
		  $start = ($page-1)*$param['rows'];
		  $page_array['sql_limit'] = "{$start},".$param['rows']; //产生sql的limit语句			  	  
		  $page_array['head'] =  $view->_write_url("$url&page=1");
		  $page_array['up'] = $view->_write_url("$url&page=$uppage");
		  $page_array['down'] = $view->_write_url("$url&page=$nextpage");
		  $page_array['foot'] = $view->_write_url("$url&page=$totalpage");
		  $page_array['totalpage'] = $totalpage;
		  $page_array['total'] = $param['total'];
					  
		 return $page_array;

    }
	
    /* 插入数据 */
    function post($data = array())
    {
		return $this->IU_Sql_Exe(array ('data' => $data, 'mode' => 'INSERT'));     
    }
    /* 最新插入id号 */
    function get_insert_id()
    {
		return $this->db->insert_id();        
    }
    function edit($id,$data = array())
    {
	    foreach($id as $key => $value){
		   $filedname = $key;
		   $filedvalue = $value;
		}
		return $this->IU_Sql_Exe(array ('data' => $data,'mode' => 'UPDATE','conditions' =>"{$filedname} = '{$filedvalue}' "));     
    }
    /* 通过id取出一条数据 */
    function oneshow($id)
    {    
	    foreach($id as $key => $value){
		   $filedname = $key;
		   $filedvalue = $value;
		}	      
		 $info = $this->S_Sql_Exe(array('fields' =>'*','conditions' =>"{$filedname}='{$filedvalue}'",'return' =>'one'));
    
		 return $info;        
    }
    /* 删除数据 */
    function del($id)
    {      
	    foreach($id as $key => $value){
		   $filedname = $key;
		   $filedvalue = $value;
		}		
		return $this->D_Sql_Exe(array ('conditions' =>"{$filedname}='{$filedvalue}' "));       
    }	
    function show($conditions='',$fields='*',$order='',$url='')
    {   	    
	      //分页时，一定是先调用page函数，再调用S_Sql_Exe函数
		 $info['page'] = $this->Page(array('conditions' =>$conditions,'url' => $url));		
		 $info['data'] = $this->S_Sql_Exe(array('fields' =>$fields,'conditions' =>$conditions,'order' =>$order,'limit' =>$info['page']['sql_limit']));   
		 return $info;
        
    }	
}









?>